import React from "react";
import ReactDOM from "react-dom";
import App from "next/app";
import Head from "next/head";
import Router from "next/router";
// redux
import withReduxSaga from "next-redux-saga";
import createWrapper from "next-redux-wrapper";
import { useStore, Provider } from "react-redux";
import { END } from "redux-saga";
import { ReactReduxContext } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";

import { wrapper } from "../redux/store";

// local components
import PageChange from "components/PageChange/PageChange.js";

import "assets/scss/nextjs-material-kit-pro.scss?v=1.1.0";

import "assets/css/react-demo.css";

import "animate.css/animate.min.css";

Router.events.on("routeChangeStart", (url) => {
  console.log(`Loading: ${url}`);
  document.body.classList.add("body-page-transition");
  ReactDOM.render(
    <PageChange path={url} />,
    document.getElementById("page-transition")
  );
});
Router.events.on("routeChangeComplete", () => {
  ReactDOM.unmountComponentAtNode(document.getElementById("page-transition"));
  document.body.classList.remove("body-page-transition");
});
Router.events.on("routeChangeError", () => {
  ReactDOM.unmountComponentAtNode(document.getElementById("page-transition"));
  document.body.classList.remove("body-page-transition");
});

function WrappedApp({ Component, pageProps }) {
  const store = useStore((state) => state);
  return (
    <PersistGate persistor={store.__persistor} loading={<div>Loading</div>}>
      <Head>
        <title>NextJS Material Kit by Creative Tim</title>
      </Head>
      <Component {...pageProps} />
    </PersistGate>
  );
}

WrappedApp.getInitialProps = async ({ Component, ctx }) => {
  // 1. Wait for all page actions to dispatch
  const pageProps = {
    ...(Component.getInitialProps ? await Component.getInitialProps(ctx) : {}),
  };

  // 2. Stop the saga if on server
  if (ctx.req) {
    ctx.store.dispatch(END);
    await ctx.store.sagaTask.toPromise();
  }

  // 3. Return props
  return {
    pageProps,
  };
};

export default wrapper.withRedux(withReduxSaga(WrappedApp));
